package com.zwl.smartplatform.service.impl;

import com.zwl.smartplatform.exceptions.AddDataException;
import com.zwl.smartplatform.exceptions.ResultCode;
import com.zwl.smartplatform.mapper.SceneMapper;
import com.zwl.smartplatform.pojo.CheckType;
import com.zwl.smartplatform.pojo.Scene;
import com.zwl.smartplatform.pojo.User;
import com.zwl.smartplatform.service.SceneService;
import com.zwl.smartplatform.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;


import java.util.Date;
import java.util.List;

@Service
@Transactional//控制事务
public class SceneServiceImpl implements SceneService {
    private SceneMapper sceneMapper;

    @Autowired
    public void setSceneMapper(SceneMapper sceneMapper) {
        this.sceneMapper = sceneMapper;
    }

    @Override
    public void addScene(Scene scene) {
        Assert.isTrue(!scene.isEmpty(CheckType.ADD),()->{
            throw new AddDataException("必须传递到数据不完整，请检查", ResultCode.USERNAME_NULL);
        });
        //我们的场景是否允许名字重复 注意是指到用一个用户是否可以创建多个相同到场景
        //不同用户到场景可以重复 所以表中到列肯定不能有唯一性到约束
        //假如我们不允许重复
        User user = SecurityUtils.getUser();
        //查询的数据
        Scene currentScene = sceneMapper.selectByUserIdAndName(user.getuId(), scene.getSceneName());

        Assert.isTrue(currentScene == null || currentScene.getStatus() == 2,()->{
            throw new AddDataException("场景已经存在",ResultCode.DATA_ALREADY_EXIST);
        });
        //更新或者删除插入
        //比如我们约定如果存在就更新数据 如果不存在就添加数据
        //判断数据是否是空的
        if(currentScene == null){
            scene.setCreateBy(user.getuId());
            scene.setCreateTime(new Date());
            sceneMapper.addScene(scene);
        }else{
            currentScene.setCreateTime(new Date());
            sceneMapper.reEnableScene(currentScene.getSceneId(),new Date());
        }



    }

    @Override
    public void updateScene(Scene scene) {

    }

    @Override
    public void deleteById(List<Long> ids, Long userId) {

    }

    @Override
    public List<Scene> findByUserId(Long userId) {
        return null;
    }
}
